//
// Created by wsl on 23-2-7.
//


#include "json_parser.h"

std::string read_from_file_as_string(const std::string& file_path)
{
    std::ifstream in(file_path, std::ios::out);
    std::stringstream buf;
    buf << in.rdbuf();
    in.close();
    return buf.str();

}

static std::string base64Decode(const char* Data, int DataByte)
{
    const char DecodeTable[] =
            {
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    62, // '+'
                    0, 0, 0,
                    63, // '/'
                    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
                    0, 0, 0, 0, 0, 0, 0,
                    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                    13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
                    0, 0, 0, 0, 0, 0,
                    26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
                    39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
            };

    std::string strDecode;
    int nValue;
    int i = 0;
    while (i < DataByte)
    {
        if (*Data != '\r' && *Data != '\n')
        {
            nValue = DecodeTable[*Data++] << 18;
            nValue += DecodeTable[*Data++] << 12;
            strDecode += (nValue & 0x00FF0000) >> 16;
            if (*Data != '=')
            {
                nValue += DecodeTable[*Data++] << 6;
                strDecode += (nValue & 0x0000FF00) >> 8;
                if (*Data != '=')
                {
                    nValue += DecodeTable[*Data++];
                    strDecode += nValue & 0x000000FF;
                }
            }
            i += 4;
        }
        else
        {
            Data++;
            i++;
        }
    }
    return strDecode;
}


void parse_json(const std::string& json_file,std::vector<std::vector<cv::Point>>&points)
{
    std::string strJsonContent = read_from_file_as_string(json_file);

    Json::Value subroot;
    Json::Reader reader;
    Json::Value root;

    if (reader.parse(strJsonContent, root))
        subroot = root["shapes"];

    //std::string imageData = root["imageData"].asString();

    for (auto & i : subroot) {
        std::vector<cv::Point> temp{};
        for (auto & j : i["points"]) {
            temp.emplace_back(j[0].asInt(),j[1].asInt());
        }
        points.push_back(temp);
    }
}